<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>compile | 掏钱的机器猫</title>
    <meta name="generator" content="VuePress 1.9.7">
    <link rel="icon" href="/vue-admin-ui/assets/logo.png">
    <meta name="description" content="掏钱的机器猫的个人博客,记录随笔与学习笔记，个人项目等">
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
    
    <link rel="preload" href="/vue-admin-ui/assets/css/0.styles.fb55c927.css" as="style"><link rel="preload" href="/vue-admin-ui/assets/js/app.21d1badc.js" as="script"><link rel="preload" href="/vue-admin-ui/assets/js/3.d02ddc64.js" as="script"><link rel="preload" href="/vue-admin-ui/assets/js/1.38c8ef5a.js" as="script"><link rel="preload" href="/vue-admin-ui/assets/js/31.036bec0e.js" as="script"><link rel="preload" href="/vue-admin-ui/assets/js/8.79ebffb7.js" as="script"><link rel="prefetch" href="/vue-admin-ui/assets/js/10.d9a14dc0.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/11.284df538.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/12.530bdb86.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/13.3dde5c1a.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/14.e18000c4.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/15.65b98979.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/16.953b2589.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/17.d6be13fa.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/18.a10ec5a3.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/19.f2ef083a.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/20.9e024a1a.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/21.b818c6cd.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/22.f3716a62.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/23.42bfb2a3.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/24.0382e6dc.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/25.9b1cf793.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/26.626abbca.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/27.d6b1a7e8.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/28.7381bce0.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/29.65b69672.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/30.70062600.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/32.1ec26c99.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/33.69485516.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/34.30a7370c.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/35.1e72f74a.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/36.a6aaafe3.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/4.984f5e20.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/5.2cbf0f84.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/6.eab8daa0.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/7.41bb2a3c.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/9.e9ae19e3.js">
    <link rel="stylesheet" href="/vue-admin-ui/assets/css/0.styles.fb55c927.css">
  </head>
  <body>
    <div id="app" data-server-rendered="true"><div class="theme-container" data-v-2d5f533b><div data-v-2d5f533b><div id="loader-wrapper" class="loading-wrapper" data-v-d48f4d20 data-v-2d5f533b data-v-2d5f533b><div class="loader-main" data-v-d48f4d20><div data-v-d48f4d20></div><div data-v-d48f4d20></div><div data-v-d48f4d20></div><div data-v-d48f4d20></div></div> <!----> <!----></div> <div class="password-shadow password-wrapper-out" style="display:none;" data-v-64685f0e data-v-2d5f533b data-v-2d5f533b><h3 class="title" style="display:none;" data-v-64685f0e data-v-64685f0e>掏钱的机器猫</h3> <!----> <label id="box" class="inputBox" style="display:none;" data-v-64685f0e data-v-64685f0e><input type="password" value="" data-v-64685f0e> <span data-v-64685f0e>Konck! Knock!</span> <button data-v-64685f0e>OK</button></label> <div class="footer" style="display:none;" data-v-64685f0e data-v-64685f0e><span data-v-64685f0e><i class="iconfont reco-theme" data-v-64685f0e></i> <a target="blank" href="https://vuepress-theme-reco.recoluan.com" data-v-64685f0e>vuePress-theme-reco</a></span> <span data-v-64685f0e><i class="iconfont reco-copyright" data-v-64685f0e></i> <a data-v-64685f0e><span data-v-64685f0e>Ethan</span>
              
            <span data-v-64685f0e>2018 - </span>
            2022
          </a></span></div></div> <div class="hide" data-v-2d5f533b><header class="navbar" data-v-2d5f533b><div class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/vue-admin-ui/" class="home-link router-link-active"><img src="/vue-admin-ui/assets/logo.png" alt="掏钱的机器猫" class="logo"> <span class="site-name">掏钱的机器猫</span></a> <div class="links"><div class="color-picker"><a class="color-button"><i class="iconfont reco-color"></i></a> <div class="color-picker-menu" style="display:none;"><div class="mode-options"><h4 class="title">Choose mode</h4> <ul class="color-mode-options"><li class="dark">dark</li><li class="auto active">auto</li><li class="light">light</li></ul></div></div></div> <div class="search-box"><i class="iconfont reco-search"></i> <input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div> <nav class="nav-links can-hide"><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-document"></i>
        插件文档
      </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/vue-admin-ui/category/vue-admin-ui-lib/" class="nav-link"><i class="iconfont undefined"></i>
    vue-admin-ui-lib
  </a></li><li class="dropdown-item"><!----> <a href="/vue-admin-ui/category/submit-valid/" class="nav-link"><i class="iconfont undefined"></i>
    submit-valid
  </a></li><li class="dropdown-item"><!----> <a href="/vue-admin-ui/category/open-utils/" class="nav-link"><i class="iconfont undefined"></i>
    open-utils
  </a></li></ul></div></div><div class="nav-item"><a href="/vue-admin-ui/handle/handle/method.html" class="nav-link"><i class="iconfont undefined"></i>
    手写代码
  </a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-message"></i>
        个人站点
      </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="https://gitee.com/ethan6" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="iconfont reco-mayun"></i>
    Gitee
    <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li><li class="dropdown-item"><!----> <a href="https://github.com/Ethan66" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="iconfont reco-github"></i>
    Github
    <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li></ul></div></div> <a href="https://github.com/Ethan66/vue-admin-ui" target="_blank" rel="noopener noreferrer" class="repo-link"><i class="iconfont reco-github"></i>
      Github
      <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></nav></div></header> <div class="sidebar-mask" data-v-2d5f533b></div> <aside class="sidebar" data-v-2d5f533b><div class="personal-info-wrapper" data-v-ca798c94 data-v-2d5f533b><img src="/vue-admin-ui/assets/logo.png" alt="author-avatar" class="personal-img" data-v-ca798c94> <h3 class="name" data-v-ca798c94>
    Ethan
  </h3> <div class="num" data-v-ca798c94><div data-v-ca798c94><h3 data-v-ca798c94>24</h3> <h6 data-v-ca798c94>文章</h6></div> <div data-v-ca798c94><h3 data-v-ca798c94>11</h3> <h6 data-v-ca798c94>标签</h6></div></div> <hr data-v-ca798c94></div> <nav class="nav-links"><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-document"></i>
        插件文档
      </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/vue-admin-ui/category/vue-admin-ui-lib/" class="nav-link"><i class="iconfont undefined"></i>
    vue-admin-ui-lib
  </a></li><li class="dropdown-item"><!----> <a href="/vue-admin-ui/category/submit-valid/" class="nav-link"><i class="iconfont undefined"></i>
    submit-valid
  </a></li><li class="dropdown-item"><!----> <a href="/vue-admin-ui/category/open-utils/" class="nav-link"><i class="iconfont undefined"></i>
    open-utils
  </a></li></ul></div></div><div class="nav-item"><a href="/vue-admin-ui/handle/handle/method.html" class="nav-link"><i class="iconfont undefined"></i>
    手写代码
  </a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-message"></i>
        个人站点
      </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="https://gitee.com/ethan6" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="iconfont reco-mayun"></i>
    Gitee
    <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li><li class="dropdown-item"><!----> <a href="https://github.com/Ethan66" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="iconfont reco-github"></i>
    Github
    <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li></ul></div></div> <a href="https://github.com/Ethan66/vue-admin-ui" target="_blank" rel="noopener noreferrer" class="repo-link"><i class="iconfont reco-github"></i>
      Github
      <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></nav> <ul class="sidebar-links"><li><section class="sidebar-group depth-0"><p class="sidebar-heading open"><span></span> <!----></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/vue-admin-ui/vue/vue/compile.html" aria-current="page" class="active sidebar-link">compile</a></li><li><a href="/vue-admin-ui/vue/vue/computed.html" class="sidebar-link">computed</a></li><li><a href="/vue-admin-ui/vue/vue/data.html" class="sidebar-link">依赖收集</a></li><li><a href="/vue-admin-ui/vue/vue/lifeCycle.html" class="sidebar-link">vue从创建到挂载的过程</a></li><li><a href="/vue-admin-ui/vue/vue/mixins.html" class="sidebar-link">mixins</a></li><li><a href="/vue-admin-ui/vue/vue/watch.html" class="sidebar-link">watch</a></li></ul></section></li></ul> </aside> <div class="password-shadow password-wrapper-in" style="display:none;" data-v-64685f0e data-v-2d5f533b><h3 class="title" style="display:none;" data-v-64685f0e data-v-64685f0e>compile</h3> <!----> <label id="box" class="inputBox" style="display:none;" data-v-64685f0e data-v-64685f0e><input type="password" value="" data-v-64685f0e> <span data-v-64685f0e>Konck! Knock!</span> <button data-v-64685f0e>OK</button></label> <div class="footer" style="display:none;" data-v-64685f0e data-v-64685f0e><span data-v-64685f0e><i class="iconfont reco-theme" data-v-64685f0e></i> <a target="blank" href="https://vuepress-theme-reco.recoluan.com" data-v-64685f0e>vuePress-theme-reco</a></span> <span data-v-64685f0e><i class="iconfont reco-copyright" data-v-64685f0e></i> <a data-v-64685f0e><span data-v-64685f0e>Ethan</span>
              
            <span data-v-64685f0e>2018 - </span>
            2022
          </a></span></div></div> <div data-v-2d5f533b><main class="page"><div class="page-title" style="display:none;"><h1 class="title">compile</h1> <div data-v-3b7f5bdf><i class="iconfont reco-account" data-v-3b7f5bdf><span data-v-3b7f5bdf>Ethan</span></i> <i class="iconfont reco-date" data-v-3b7f5bdf><span data-v-3b7f5bdf>2020-10-23</span></i> <!----> <i class="iconfont reco-tag tags" data-v-3b7f5bdf><span class="tag-item" data-v-3b7f5bdf>vue2源码</span></i></div></div> <div class="theme-reco-content content__default" style="display:none;"><h1 id="compile"><a href="#compile" class="header-anchor">#</a> compile</h1> <h2 id="导读"><a href="#导读" class="header-anchor">#</a> 导读</h2> <p><a href="https://mp.weixin.qq.com/s?__biz=MzUxNjQ1NjMwNw==&amp;mid=2247484386&amp;idx=1&amp;sn=b901d961488a6f52e9a14756c34d445d&amp;chksm=f9a669feced1e0e8197c5f3c30410eef79deb3d3ab9a2352c0813ef6b5f1f8800f79f92769d7&amp;scene=21#wechat_redirect" target="_blank" rel="noopener noreferrer">白话版<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> // 为主
<a href="https://cloud.tencent.com/developer/article/1479312" target="_blank" rel="noopener noreferrer">parese<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> // 看总结的上面一段
<a href="https://cloud.tencent.com/developer/article/1479404" target="_blank" rel="noopener noreferrer">optimize<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> // 好累，看：逐行剖析 Vue.js 源码
<a href="https://cloud.tencent.com/developer/article/1479388" target="_blank" rel="noopener noreferrer">generate<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> // 好累，看：逐行剖析 Vue.js 源码</p> <blockquote><p>若options.render存在，则没有compile这步，vue直接执行options.render函数
compile的作用是把template模板解析生产成render函数，render函数执行后就生成了对应的Vnode。
compile的三步骤：Parse（将template模板生成ast节点(抽象语法树)），Optimize（遍历ast节点，标记为静态的节点，生成新的ast节点(抽象语法树)），Generate（将新的ast节点生成render字符串）。
render字符串转为render函数：render = new Function(render)，将render函数保存在vm.$options.render上。</p></blockquote> <h2 id="什么时候执行"><a href="#什么时候执行" class="header-anchor">#</a> 什么时候执行</h2> <p>在created和beforeCreate之间，判断$options.render是否存在，不存在，获取template字符串，调用compileToFunctions(template)，compileToFunctions有compile函数，生成render函数。compile函数包含了parse函数, optimize函数, generate函数。</p> <h2 id="parse"><a href="#parse" class="header-anchor">#</a> Parse</h2> <p>接收template原始模板，按照模板的节点和数据生成对应的ast（抽象语法树）</p> <div class="code-wrap"><!----> <div class="code--demo"><div class="code-content"><div>template执行了Parse后的结果。template：<span>&lt;div test=2&gt;&lt;span name=1&gt;&lt;/span&gt;&lt;/div&gt;</span></div> <div class="code-tips"></div></div></div> <div class="code--segment"><highlight-code lang="js">
    // result
    {    
      tag: &quot;div&quot;,    
      attrsMap: {test: &quot;2&quot;},    
      children:[{        
        tag: &quot;span&quot;,        
        children: [],        
        attrsMap: {name: &quot;1&quot;}
      }]
    }
  </highlight-code></div> <div class="code--button">显示代码</div></div> <h2 id="optimize"><a href="#optimize" class="header-anchor">#</a> Optimize</h2> <p>遍历递归每一个ast节点，找出所有的静态节点打标，找出所有的静态根节点打标。标记静态的节点（没有绑定任何动态数据staticRoot: true）。这样就知道那部分不会变化，于是在页面需要更新时，直接clone就可以了，减少去比对这部分DOM。从而达到性能优化的目的。</p> <ul><li>怎么判断是否是静态节点：</li> <li><ol><li>从ast根节点开始遍历，false为动态，说明不是静态节点</li></ol></li> <li><ol start="2"><li>node.type === 2，动态的文本节点，返回false</li></ol></li> <li><ol start="3"><li>node.type === 3，纯文本，返回true</li></ol></li> <li><ol start="4"><li>node.type === 1，元素节点，进一步判断</li></ol></li> <li><ol start="5"><li>存在v-pre返回true；否则不存在特殊指令v-if,v-else，不存在slot和component，不存在特殊组件，节点的父节点不能带v-for，template，才能返回true</li></ol></li> <li><ol start="6"><li>节点的返回的true，但是节点的子节点返回false，那么此节点要改回false</li></ol></li> <li>找出所有的静态节点，再找出静态根节点：</li> <li><ol><li>从ast根节点开始遍历：节点为静态节点，且节点存在子节点()，且节点不能只有一个文本节点，才能是静态根节点</li></ol></li></ul> <div class="code-wrap"><!----> <div class="code--demo"><div class="code-content"><div>ast执行了optimize后的结果。template：<span>&lt;div&gt;&lt;span&gt;1&lt;/span&gt;{{a}}&lt;/div&gt;</span></div> <div class="code-tips"></div></div></div> <div class="code--segment"><highlight-code lang="js">
    // optimize
    {    
      tag: &quot;div&quot;,    
      children:[{
        staticRoot: true, // optimize后的静态根节点标识
        tag: &quot;span&quot;,        
        children: [{
          static: true, // optimize后的静态文本的标识
          text: '1'
        }]   
      }, {
        static: false, // 表示不是静态节点
        text: '\{\{a\}\}' // 表示双括号a
      }]
    }
  </highlight-code></div> <div class="code--button">显示代码</div></div> <h2 id="generate"><a href="#generate" class="header-anchor">#</a> Generate</h2> <p>把前两步生成完善的 ast 组装成 render 字符串（后面通过createFunction(render)转成函数），保存到vm.$options.render</p> <div class="code-wrap"><!----> <div class="code--demo"><div class="code-content"><div>template执行了Parse后的结果。template：<span>&lt;div&gt;&lt;span&gt;{{b}}&lt;/span&gt;{{a}}&lt;/div&gt;</span></div> <div class="code-tips"></div></div></div> <div class="code--segment"><highlight-code lang="js">
    // 前两步后的ast
    {    
      static: false,    
      staticRoot: false,    
      tag: &quot;div&quot;,    
      children: [{        
        static: false,        
        staticRoot: false,        
        tag: &quot;span&quot;,        
        children: [{            
          static: false,            
          text: &quot;\{\{b\}\}&quot; // 实际为双大括号a，加\是为了显示出来
        }]
      },{        
          static: false,        
          text: &quot;\{\{a\}\}&quot; // 实际为双大括号a，加\是为了显示出来
      }]
    }
<div class="language- extra-class"><pre><code>// 经过generate的流程
// 1、处理最外层的div, code = `_c('div', [`
// 2、遍历div子节点，遇到span, code = `_c('div', [ _c('span', [`
// 3、遇到span的子节点b, code = `_c('div', [ _c('span', [ _v(b)`
// 4、span子节点处理完成，闭合span的子节点数组, code = `_c('div', [ _c('span', [ _v(b) ]`
// 5、处理span同级子节点, code = `_c('div', [ _c('span', [ _v(b) ], _v(a)`
// 6、所有子节点处理完成，闭合div的子节点数组, code = `_c('div', [ _c('span', [ _v(b) ], _v(a) )]`
</code></pre></div></highlight-code></div> <div class="code--button">显示代码</div></div> <h2 id="源码"><a href="#源码" class="header-anchor">#</a> 源码</h2> <h3 id="parse-2"><a href="#parse-2" class="header-anchor">#</a> Parse</h3> <ul><li>template: &lt;div&gt;11&lt;/div&gt;</li> <li><ol><li>while遍历template，匹配到&lt;div&gt;，执行start方法，将div转为ast节点element，当前没有root节点，将root = element，（若有currentParent，currentParent.children.push(element)），设置currentParent = element，将element保存进节点缓存数组stack，stack === [ {tag:'div' , children:[ ] } ]</li></ol></li> <li><ol start="2"><li>第一轮结束。template === 11&lt;/div&gt;</li></ol></li> <li><ol start="3"><li>开头不是&lt;，执行char方法，执行currentParent.children.push({ type:3 , text:'11' })，stack === [ { tag:'div' , children:[ { type:3 , text:'11' } ] } ]</li></ol></li> <li><ol start="4"><li>第二轮结束。template: &lt;/div&gt;</li></ol></li> <li><ol start="5"><li>匹配到是结束标签，执行end方法，删除stack的最后一项，currentParent为stack的倒数第二项</li></ol></li> <li><ol start="6"><li>遍历结束，返回root。</li></ol></li></ul> <div class="code-wrap"><!----> <div class="code--demo"><div class="code-content"><div>parse(template)，针对一般template复现，不考虑特殊情况（没有结束标签，文本存在&lt;，注释等）</div> <div class="code-tips"></div></div></div> <div class="code--segment"><highlight-code lang="js">
    // 开始解析template
    function parse(template) {
      var stack = [] // 闭包：缓存每个头标签，最后一个头标签表示当前标签的父节点
      var root // 闭包：根节点，最终的ast节点保存在这里
      var currentParent // 闭包：当前标签的父节点
      parseHTML(template, {
        start, // 开始标签处理函数
        end, // 结束标签处理函数
        chars // 文本处理函数
      })
      return root
    }
<div class="language- extra-class"><pre><code>function parseHTML(html, options) {
  while(html) {
    var textEnd = html.indexOf('&lt;'),
        text, rest, next
    // html以&lt;开头
    if (textEnd === 0) {
      var endTagMatch = html.match(/^&lt;\/[\w-]+?&gt;/) // 是尾标签
      if (endTagMatch) {
        html = html.substring(endTagMatch[0].length) // html截掉尾标签
        options.end() // stack最后一项去掉，currentParent为stack的最后一项
        continue
      }
    }
    var startTagMatch = html.match(/^&lt;[\w-]+?&gt;/)
    if (startTagMatch) { // 是头标签
      startTagMatch = parseStartTag() // 没写：将头标签根据正则取出每一个属性，转为{tagName: 'div', attrs: [{ name: 1 }]}
      optioins.start(startTagMatch) // 转为ast节点，将ast节点保存到currentParent.children中
      continue
    }
    if (textEnd &gt; 0) { // 是文本
      text = html.substring(0, textEnd)
      html = html.substring(text.length)
    }
    if (options.chars &amp;&amp; text) {
      options.chars(text) // 将文本保存到currentParent.children中
    }
  }
}

// 辅助函数: 处理头标签
function start(tag, attrs, unary) {
  var element = createASTElement(tag, attrs, currentParent) // 创建ast节点
  // 省略了v-for, v-if等指令
  if (!root) root = element
  if (currentParent) {
    // 把节点添加到父节点的children中
    currentParent.children.push(element)
    element.parent = currentParent
  }
  if (!unary) { // 不是单标签才存入stack
    currentParent = element
    stack.push(element)
  }
}

// 辅助函数
function createASTElement(tag, attrs, parent) {
  return {        
    type: 1,        
    tag: tag,        
    attrsList: attrs,        
    // 把attrs数组转成对象
    attrsMap: makeAttrsMap(attrs),        
    parent: parent,        
    children: []
  }
}

// 辅助函数：处理尾标签
function end() {    
  // 标签解析结束，移除该标签
  stack.length -= 1
  currentParent = stack[stack.length - 1]
}

// 辅助函数：处理文本
function chars(text) {    
  // 必须存在根节点，不可能用文字开头
  if(!currentParent) return
  var children = currentParent.children   
  // 通过 parseText 解析成字符串，判断是否含有双括号表达式，比如 \{\{a\}\}
  // 如果是有表达式，会存放多一些信息，
  var res = parseText(text)    
  if(res) {
    children.push({            
      type: 2,            
      expression: res.expression, // &quot;我叫&quot;+_s(name)+&quot;，我今年&quot;+_s(age)+&quot;岁了&quot;         
      tokens: res.tokens, // [&quot;我叫&quot;, {'@binding': name }, &quot;，我今年&quot;, {'@binding': age }, &quot;岁了&quot;]           
      text: text // 我叫\{\{name\}\}，我今年\{\{age\}\}岁了&quot;
    })
  }    
  // 普通字符串，直接存为 字符串子节点
  else if(
    !children.length ||
    children[children.length - 1].text !== ' '
  ) {
    children.push({            
      type: 3,            
      text: text
    })
  }
}
</code></pre></div></highlight-code></div> <div class="code--button">显示代码</div></div></div> <footer class="page-edit" style="display:none;"><!----> <div class="last-updated"><span class="prefix">上次更新: </span> <span class="time">2022/7/8 上午10:51:20</span></div></footer> <!----> <!----> <!----></main> <!----></div></div></div></div><div class="global-ui"><div class="back-to-ceiling" style="right:1rem;bottom:6rem;width:2.5rem;height:2.5rem;border-radius:.25rem;line-height:2.5rem;display:none;" data-v-c6073ba8 data-v-c6073ba8><svg t="1574745035067" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5404" class="icon" data-v-c6073ba8><path d="M526.60727968 10.90185116a27.675 27.675 0 0 0-29.21455937 0c-131.36607665 82.28402758-218.69155461 228.01873535-218.69155402 394.07834331a462.20625001 462.20625001 0 0 0 5.36959153 69.94390903c1.00431239 6.55289093-0.34802892 13.13561351-3.76865779 18.80351572-32.63518765 54.11355614-51.75690182 118.55860487-51.7569018 187.94566865a371.06718723 371.06718723 0 0 0 11.50484808 91.98906777c6.53300375 25.50556257 41.68394495 28.14064038 52.69160883 4.22606766 17.37162448-37.73630017 42.14135425-72.50938081 72.80769204-103.21549295 2.18761121 3.04276886 4.15646224 6.24463696 6.40373557 9.22774369a1871.4375 1871.4375 0 0 0 140.04691725 5.34970492 1866.36093723 1866.36093723 0 0 0 140.04691723-5.34970492c2.24727335-2.98310674 4.21612437-6.18497483 6.3937923-9.2178004 30.66633723 30.70611158 55.4360664 65.4791928 72.80769147 103.21549355 11.00766384 23.91457269 46.15860503 21.27949489 52.69160879-4.22606768a371.15156223 371.15156223 0 0 0 11.514792-91.99901164c0-69.36717486-19.13165746-133.82216804-51.75690182-187.92578088-3.42062944-5.66790279-4.76302748-12.26056868-3.76865837-18.80351632a462.20625001 462.20625001 0 0 0 5.36959269-69.943909c-0.00994388-166.08943902-87.32547796-311.81420293-218.6915546-394.09823051zM605.93803103 357.87693858a93.93749974 93.93749974 0 1 1-187.89594924 6.1e-7 93.93749974 93.93749974 0 0 1 187.89594924-6.1e-7z" p-id="5405" data-v-c6073ba8></path><path d="M429.50777625 765.63860547C429.50777625 803.39355007 466.44236686 1000.39046097 512.00932183 1000.39046097c45.56695499 0 82.4922232-197.00623328 82.5015456-234.7518555 0-37.75494459-36.9345906-68.35043303-82.4922232-68.34111062-45.57627738-0.00932239-82.52019037 30.59548842-82.51086798 68.34111062z" p-id="5406" data-v-c6073ba8></path></svg></div></div></div>
    <script src="/vue-admin-ui/assets/js/app.21d1badc.js" defer></script><script src="/vue-admin-ui/assets/js/3.d02ddc64.js" defer></script><script src="/vue-admin-ui/assets/js/1.38c8ef5a.js" defer></script><script src="/vue-admin-ui/assets/js/31.036bec0e.js" defer></script><script src="/vue-admin-ui/assets/js/8.79ebffb7.js" defer></script>
  </body>
</html>
